package com.paw.core.config;

import java.time.LocalDateTime;
import java.util.Date;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.paw.common.context.UserContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * 填充字段
 */
public class MyMetaObjectHandler implements MetaObjectHandler {


  @Override
  public void insertFill (MetaObject metaObject) {
    String operator = getOperator();
    Date date = new Date();
    this.strictInsertFill(metaObject, "createTime", ()->date, Date.class);
    this.strictInsertFill(metaObject, "updateTime", ()->date, Date.class);
    this.strictInsertFill(metaObject, "createBy", ()->operator, String.class);
    this.strictInsertFill(metaObject, "updateBy", ()->operator, String.class);
  }

  @Override
  public void updateFill (MetaObject metaObject) {
    String operator = getOperator();
    this.strictUpdateFill(metaObject, "updateTime", Date::new, Date.class);
    this.strictUpdateFill(metaObject, "updateBy", ()->operator, String.class);
  }

  private String getOperator () {
    String operator = UserContextHolder.getUser().getName()!=null?UserContextHolder.getUser().getName():"sys";
    return operator;
  }
}
